package com.netty.server.handler;

import com.netty.server.base.RequestRegister;
import com.netty.server.cmd.ByteCmd;
import com.netty.server.processor.DownProcessor;
import com.netty.server.sender.CmdRequest;
import com.netty.server.sender.CmdResponse;
import com.netty.server.utils.CmdIdGenerator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.util.List;

public class RegisterHandler extends MessageToMessageCodec<CmdResponse, CmdRequest> {

    private final RequestRegister register;
    private final DownProcessor downProcessor;
    private final CmdIdGenerator cmdIdGenerator;

    public RegisterHandler(RequestRegister register,
                           DownProcessor downProcessor,
                           CmdIdGenerator cmdIdGenerator) {
        this.register = register;
        this.downProcessor = downProcessor;
        this.cmdIdGenerator = cmdIdGenerator;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, CmdRequest request, List<Object> list) throws Exception {
        //生成CmdId
        long cmdId = cmdIdGenerator.nextCmdId();
        request.setCmdId(cmdId);
        //注册
        register.register(request);
        //发送
        ByteCmd byteCmd = downProcessor.processor(request);
        list.add(byteCmd);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, CmdResponse cmdResponse, List<Object> list) throws Exception {
        // 收到响应进行处理
        register.handle(cmdResponse);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 在channel不活跃后，释放register
        register.release();
        super.channelInactive(ctx);
    }
}
